'use client'

import { createContext, useContext, useEffect, useState } from 'react'
import type { ThemeColor } from '@/lib/theme-config'
import { DEFAULT_THEME, getThemeConfig, isValidTheme } from '@/lib/theme-config'

interface ThemeContextType {
  theme: ThemeColor
  setTheme: (theme: ThemeColor) => void
  isDark: boolean
  setIsDark: (isDark: boolean) => void
}

const ThemeContext = createContext<ThemeContextType | undefined>(undefined)

interface ThemeProviderProps {
  children: React.ReactNode
  defaultTheme?: ThemeColor
  storageKey?: string
}

export function ThemeProvider({
  children,
  defaultTheme = DEFAULT_THEME,
  storageKey = 'ui-theme',
}: ThemeProviderProps) {
  const [theme, setThemeState] = useState<ThemeColor>(defaultTheme)
  const [isDark, setIsDarkState] = useState(false)

  // 从localStorage加载主题设置
  useEffect(() => {
    try {
      const storedTheme = localStorage.getItem(storageKey)
      const storedDarkMode = localStorage.getItem(`${storageKey}-dark`)
      
      if (storedTheme && isValidTheme(storedTheme)) {
        setThemeState(storedTheme)
      }
      
      if (storedDarkMode) {
        setIsDarkState(storedDarkMode === 'true')
      } else {
        // 检测系统主题偏好
        const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
        setIsDarkState(prefersDark)
      }
    } catch (error) {
      console.warn('Failed to load theme from localStorage:', error)
    }
  }, [storageKey])

  // 应用主题到DOM
  useEffect(() => {
    const root = document.documentElement
    const themeConfig = getThemeConfig(theme)
    
    // 设置CSS自定义属性
    root.style.setProperty('--theme-primary', `oklch(${themeConfig.oklch})`)
    root.style.setProperty('--theme-primary-hex', themeConfig.hex)
    
    // 更新dark class
    if (isDark) {
      root.classList.add('dark')
    } else {
      root.classList.remove('dark')
    }
    
    // 保存到localStorage
    try {
      localStorage.setItem(storageKey, theme)
      localStorage.setItem(`${storageKey}-dark`, isDark.toString())
    } catch (error) {
      console.warn('Failed to save theme to localStorage:', error)
    }
  }, [theme, isDark, storageKey])

  const setTheme = (newTheme: ThemeColor) => {
    setThemeState(newTheme)
  }

  const setIsDark = (newIsDark: boolean) => {
    setIsDarkState(newIsDark)
  }

  const value = {
    theme,
    setTheme,
    isDark,
    setIsDark,
  }

  return (
    <ThemeContext.Provider value={value}>
      {children}
    </ThemeContext.Provider>
  )
}

export function useTheme() {
  const context = useContext(ThemeContext)
  
  if (context === undefined) {
    throw new Error('useTheme must be used within a ThemeProvider')
  }
  
  return context
}